import i18n from "../../i18n/i18n";
import {configChange} from "../Config";
import {isFunction} from "../utils";

const reducerMap: any = import.meta.glob('./*.tsx', {eager: true});
configChange((config: any) => {
    if (isFunction(config.expandReducer)) {
        let map: any = config.expandReducer();
        for (let item: string in map) {
            const key: string = map[item].default.namespace;
            reducerMap[key] = map[item].default;
        }
    }
});

const initReducer: Function = (): void => {
    // @ts-ignore
    for (let item: string in reducerMap) {
        if (item.indexOf(".tsx") !== -1) {
            const key: string = reducerMap[item].default.namespace;
            reducerMap[key] = reducerMap[item].default;
            delete reducerMap[item];
        }
    }
};

// @ts-ignore
const coreReducer: Function = (state: any = {}, action: any) => {
    if (!action?.type || action.type.indexOf(`/`) === -1) {
        throw new Error(i18n.t("notSuccessStoreType"));
    }
    const typeArr: string[] = action.type.split('/');
    const reducerName: string = typeArr[0];
    const reducer: any = reducerMap[reducerName];
    const initState: any = {};

    // @ts-ignore
    for (let item: string in reducerMap) {
        initState[item] = reducerMap[item].state || {}
    }
    if (!reducer) {
        return initState;
    }
    initState[reducerName] = reducer[typeArr[1]](action?.payload);

    // @ts-ignore
    reducer.state = initState[reducerName];

    return initState
};

initReducer();

export default coreReducer;